<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import {
  Table as ATable,
  Card as ACard,
  Button as AButton,
  Input as AInput,
  message,
  Popconfirm as APopconfirm,
  Select as ASelect,
  SelectOption as ASelectOption,
  Tag as ATag,
  Statistic as AStatistic,
  Row as ARow,
  Col as ACol,
  type TableColumnsType
} from 'ant-design-vue'
import {
  SearchOutlined,
  DownloadOutlined,
  DeleteOutlined,
  EditOutlined,
  EyeOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import { getLearningMaterialList, getDailyUploadStats, getAuditStats } from '@/api/material'

// 学习资料数据接口定义
interface MaterialData {
  id: number
  title: string
  description: string
  fileName: string
  filePath: string
  fileSize: number
  fileType: string
  collegeName: string
  subjectType: string
  uploaderId: number
  uploaderName: string
  auditStatus: number // 0-待审核, 1-通过, 2-拒绝
  auditTime: string
  downloadCount: number
  createTime: string
  updateTime: string
}


// 搜索表单
const searchForm = reactive({
  keyword: '',
  collegeName: '',
  subjectType: '',
  auditStatus: undefined as number | undefined
})


// 响应式数据
const loading = ref(false)
const dataSource = ref<MaterialData[]>([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50'],
  showTotal: (total: number) => `共 ${total} 条`
})

// 学院选项
const collegeOptions = [
  { value: '计算机学院', label: '计算机学院' },
  { value: '电子信息学院', label: '电子信息学院' },
  { value: '机械工程学院', label: '机械工程学院' },
  { value: '经济管理学院', label: '经济管理学院' },
  { value: '外国语学院', label: '外国语学院' },
  { value: '艺术学院', label: '艺术学院' },
  { value: '土木工程学院', label: '土木工程学院' },
  { value: '化学与化工学院', label: '化学与化工学院' }
]

// 学科分类选项
const subjectOptions = [
  { value: '计算机科学', label: '计算机科学' },
  { value: '软件工程', label: '软件工程' },
  { value: '电子工程', label: '电子工程' },
  { value: '机械设计', label: '机械设计' },
  { value: '经济学', label: '经济学' },
  { value: '管理学', label: '管理学' },
  { value: '英语', label: '英语' },
  { value: '艺术设计', label: '艺术设计' },
  { value: '土木工程', label: '土木工程' },
  { value: '化学工程', label: '化学工程' },
  { value: '数学', label: '数学' },
  { value: '物理', label: '物理' },
  { value: '其他', label: '其他' }
]

// 审核状态选项
const auditStatusOptions = [
  { value: 0, label: '待审核', color: 'orange' },
  { value: 1, label: '已通过', color: 'green' },
  { value: 2, label: '已拒绝', color: 'red' }
]

// 表格列定义
const columns: TableColumnsType<MaterialData> = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '资料标题',
    dataIndex: 'title',
    width: 200,
    ellipsis: true
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: 200,
    ellipsis: true
  },
  {
    title: '文件名',
    dataIndex: 'fileName',
    width: 150,
    ellipsis: true
  },
  {
    title: '文件类型',
    dataIndex: 'fileType',
    width: 100,
    customRender: ({ text }) => {
      const typeColors: Record<string, string> = {
        'pdf': 'red',
        'doc': 'blue',
        'docx': 'blue',
        'ppt': 'orange',
        'pptx': 'orange',
        'xls': 'green',
        'xlsx': 'green',
        'txt': 'default',
        'zip': 'purple',
        'rar': 'purple'
      }
      return h(ATag, { color: typeColors[text?.toLowerCase()] || 'default' }, () => text?.toUpperCase())
    }
  },
  {
    title: '文件大小',
    dataIndex: 'fileSize',
    width: 100,
    customRender: ({ text }) => formatFileSize(text)
  },
  {
    title: '学院',
    dataIndex: 'collegeName',
    width: 120,
    ellipsis: true
  },
  {
    title: '学科分类',
    dataIndex: 'subjectType',
    width: 100
  },
  {
    title: '上传者',
    dataIndex: 'uploaderName',
    width: 100
  },
  {
    title: '审核状态',
    dataIndex: 'auditStatus',
    width: 100,
    customRender: ({ text }) => {
      const status = auditStatusOptions.find(item => item.value === text)
      return h(ATag, { color: status?.color }, () => status?.label || '未知')
    }
  },
  {
    title: '下载次数',
    dataIndex: 'downloadCount',
    width: 100
  },
  {
    title: '上传时间',
    dataIndex: 'createTime',
    width: 180,
    customRender: ({ text }) => new Date(text).toLocaleString()
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    customRender: ({ record }) => {
      return h('div', { class: 'action-buttons' }, [
        h(AButton, {
          type: 'link',
          icon: h(EyeOutlined),
          onClick: () => handleView(record)
        }, () => '查看'),
        h(AButton, {
          type: 'link',
          icon: h(DownloadOutlined),
          onClick: () => handleDownload(record)
        }, () => '下载'),
        h(AButton, {
          type: 'link',
          icon: h(EditOutlined),
          onClick: () => handleEdit(record)
        }, () => '编辑'),
        h(APopconfirm, {
          title: '确定要删除这个资料吗？',
          onConfirm: () => handleDelete(record.id)
        }, {
          default: () => h(AButton, {
            type: 'link',
            danger: true,
            icon: h(DeleteOutlined)
          }, () => '删除')
        })
      ])
    }
  }
]

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取资料列表
const fetchMaterialList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }
    
    const response = await getLearningMaterialList(params)
    
    if (response.data.code === 200) {
      dataSource.value = response.data.data.records || []
      pagination.total = response.data.data.total || 0
    } else {
      message.error(response.data.message || '获取资料列表失败')
    }
  } catch (error) {
    console.error('获取资料列表失败:', error)
    message.error('获取资料列表失败')
  } finally {
    loading.value = false
  }
}

// 获取每日上传统计数据
const fetchDailyUploadStats = async () => {
  try {
    const response = await getDailyUploadStats()
    console.log('每日上传统计接口返回数据:', response)
    
    if (response.data.code === 200) {
      console.log('每日上传统计数据:', response.data.data)
    } else {
      message.error(response.data.message || '获取每日上传统计失败')
    }
  } catch (error) {
    console.error('获取每日上传统计失败:', error)
    message.error('获取每日上传统计失败')
  }
}

// 获取审核统计数据
const fetchAuditStats = async () => {
  try {
    const response = await getAuditStats()
    console.log('审核统计接口返回数据:', response)
    
    if (response.data.code === 200) {
      console.log('审核统计数据:', response.data.data)
    } else {
      message.error(response.data.message || '获取审核统计失败')
    }
  } catch (error) {
    console.error('获取审核统计失败:', error)
    message.error('获取审核统计失败')
  }
}

// 获取所有统计数据
const fetchAllStats = async () => {
  await Promise.all([
    fetchDailyUploadStats(),
    fetchAuditStats()
  ])
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchMaterialList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    collegeName: '',
    subjectType: '',
    auditStatus: undefined
  })
  pagination.current = 1
  fetchMaterialList()
}

// 编辑资料 - 管理员不可修改，仅查看
const handleEdit = (record: MaterialData) => {
  message.info('管理员无权修改资料内容，只能查看')
}

// 查看资料详情
const handleView = (record: MaterialData) => {
  // 这里可以打开详情模态框或跳转到详情页面
  message.info('查看资料详情功能待实现')
}

// 下载资料
const handleDownload = (record: MaterialData) => {
  // 这里实现文件下载逻辑
  if (record.filePath) {
    const link = document.createElement('a')
    link.href = record.filePath
    link.download = record.fileName
    link.click()
    message.success('开始下载')
  } else {
    message.error('文件路径不存在')
  }
}

// 删除资料 - 管理员不可删除
const handleDelete = async (id: number) => {
  message.info('管理员无权删除资料')
}


// 表格分页变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchMaterialList()
}


// 组件挂载时获取数据
onMounted(() => {
  fetchMaterialList()
  fetchAllStats()
})
</script>

<template>
  <div class="material-management">
    <!-- 统计数据区域 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :xs="24" :sm="12" :md="6">
        <a-card class="stats-card">
            <a-statistic
              title="总资料数"
              :value="0"
            >
            <template #prefix>
              <FileTextOutlined style="color: #1890ff" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :md="6">
        <a-card class="stats-card">
            <a-statistic
              title="待审核"
              :value="0"
            >
            <template #prefix>
              <ClockCircleOutlined style="color: #faad14" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :md="6">
        <a-card class="stats-card">
            <a-statistic
              title="已通过"
              :value="0"
            >
            <template #prefix>
              <CheckCircleOutlined style="color: #52c41a" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :md="6">
        <a-card class="stats-card">
            <a-statistic
              title="已拒绝"
              :value="0"
            >
            <template #prefix>
              <CloseCircleOutlined style="color: #f5222d" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 每日上传统计 -->
    <a-card class="daily-stats-card" title="近期上传统计">
      <div class="daily-stats-content">
        <div class="no-data">
          暂无统计数据（请查看控制台日志）
        </div>
      </div>
    </a-card>

    <!-- 搜索区域 -->
    <a-card class="search-card">
      <div class="search-form">
        <a-input
          v-model:value="searchForm.keyword"
          placeholder="搜索资料标题或描述"
          allow-clear
          style="width: 200px"
          @pressEnter="handleSearch"
        >
          <template #prefix>
            <SearchOutlined />
          </template>
        </a-input>
        
        <a-select
          v-model:value="searchForm.collegeName"
          placeholder="选择学院"
          allow-clear
          style="width: 150px"
        >
          <a-select-option v-for="college in collegeOptions" :key="college.value" :value="college.value">
            {{ college.label }}
          </a-select-option>
        </a-select>
        
        <a-select
          v-model:value="searchForm.subjectType"
          placeholder="选择学科"
          allow-clear
          style="width: 120px"
        >
          <a-select-option v-for="subject in subjectOptions" :key="subject.value" :value="subject.value">
            {{ subject.label }}
          </a-select-option>
        </a-select>
        
        <a-select
          v-model:value="searchForm.auditStatus"
          placeholder="审核状态"
          allow-clear
          style="width: 120px"
        >
          <a-select-option v-for="status in auditStatusOptions" :key="status.value" :value="status.value">
            {{ status.label }}
          </a-select-option>
        </a-select>
        
        <a-button type="primary" @click="handleSearch">
          <SearchOutlined />
          搜索
        </a-button>
        
        <a-button @click="handleReset">重置</a-button>
      </div>
    </a-card>

    <!-- 表格区域 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :scroll="{ x: 1500 }"
        row-key="id"
        @change="handleTableChange"
      />
    </a-card>

  </div>
</template>

<style scoped>
.material-management {
  padding: 0;
}

.stats-row {
  margin-bottom: 16px;
}

.stats-card {
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
}

.stats-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

:deep(.ant-statistic-title) {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

:deep(.ant-statistic-content) {
  font-size: 24px;
  font-weight: bold;
}

.daily-stats-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.daily-stats-content {
  min-height: 100px;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

.stats-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  justify-content: space-between;
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  min-width: 80px;
  transition: all 0.3s;
}

.stats-item:hover {
  background: #e3f2fd;
  transform: translateY(-1px);
}

.stats-item .date {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.stats-item .count {
  font-size: 16px;
  font-weight: bold;
  color: #1890ff;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.table-card {
  min-height: 500px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}


:deep(.ant-table-cell) {
  vertical-align: top;
}

:deep(.ant-btn-link) {
  padding: 0;
  height: auto;
}
</style>
